package com.xiaoyg.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectUtil {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //1、获取Class对象
        Class studentClass = Class.forName("com.xiaoyg.reflect.Student");
        //2、获取声明的构造函数，传入所需要的参数的类名，用,链接即可
        Constructor declaredConstructor = studentClass.getDeclaredConstructor(String.class);
        //3、私有构造函数，添加一行代码。公有的不需要
        declaredConstructor.setAccessible(true);
        //反射调用构造函数
        Object student = declaredConstructor.newInstance("nameA");
        //获取声明字段
        Field studentAge = studentClass.getDeclaredField("studentAge");

        //调用属性设置值
        studentAge.set(student, 10);

        //获取方法反射调用方法
        Method method = studentClass.getDeclaredMethod("show", String.class);
        method.setAccessible(true);

        Object message = method.invoke(student, "message");

        System.out.printf("result: "+message);



    }

}
